package com.hliushi.oauth2.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author llhuang10
 */
@Configuration
// 将此注释添加到@Configuration类，以在任何WebSecurityConfigurer定义 Spring Security 配置，或者更有可能通过扩展WebSecurityConfigurerAdapter基类并覆盖单个方法：
@EnableWebSecurity      // 启动webSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    /**
     * 用于编码密码的服务接口。 首选实现是BCryptPasswordEncoder
     *
     * @param
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {

        return super.authenticationManagerBean();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // csrf().disable()关闭了 csrf防护
        http.csrf().disable()
                // 允许了所有用户访问  /oauth/** , /login/**, /logout/** 下面所有方法
                .authorizeRequests()
                .antMatchers("/oauth/**", "/login/**", "/logout/**").permitAll()
                // 然后把剩下的所有请求, 都需要认证之后才能才能访问
                .anyRequest()
                .authenticated()
                .and()
                .formLogin().permitAll();
    }
}
